package distributedLock.sync;

import cn.hutool.core.util.ObjectUtil;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessLock;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class SyncSellTicketClass {

    @Autowired
    CuratorFramework curatorFramework;

    private static InterProcessLock lock = null;

    public void sellTicket(Integer ticketCount) {
        synchronized (this) {
            if (ObjectUtil.isNull(lock)) {
                // 构建一个互斥锁
                lock = new InterProcessMutex(curatorFramework, "/locks");
            }
        }
        try {
            while (true) {
                boolean acquire = lock.acquire(5, TimeUnit.SECONDS); // 加锁
                if (acquire) {
                    break;
                }
            }
            ticketCount--;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                lock.release(); // 释放锁
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
}
